package com.spzx.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.spzx.common.core.web.controller.BaseController;
import com.spzx.common.core.web.domain.AjaxResult;
import com.spzx.common.core.web.page.TableDataInfo;
import com.spzx.domain.ProductUnit;
import com.spzx.service.ProductUnitService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.websocket.server.PathParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

@Tag(name = "商品数量单位管理接口")
@RestController
@RequestMapping("/productunit")
public class ProductUnitController extends BaseController {
    @Autowired
    ProductUnitService productUnitService;

    @Operation(summary = "分页查询商品数量单位")
    @GetMapping("/list")
    public TableDataInfo list( ProductUnit productUnit) {
        startPage();
        List<ProductUnit> list = productUnitService.getList(productUnit);
        TableDataInfo tableDataInfo = new TableDataInfo(list,productUnitService.list().size());
        return tableDataInfo;
    }

    @GetMapping("/{id}")
    @Operation(summary = "商品数量单位详情")
    public AjaxResult getDetils(@PathVariable("id") Long id) {
        ProductUnit one = productUnitService.getOne(Wrappers.lambdaQuery(ProductUnit.class).eq(ProductUnit::getId, id));
        return AjaxResult.success(one);
    }
    @PutMapping("save")
    @Operation(summary = "新增商品数量单位")
    public AjaxResult save(@RequestBody @Validated ProductUnit productUnit){
        String name = productUnit.getName();
        ProductUnit one = productUnitService.getOne(Wrappers.lambdaQuery(ProductUnit.class).eq(ProductUnit::getName, name));
        if (one!=null){
            return AjaxResult.error("该单位已经存在");
        }
        boolean save = productUnitService.save(productUnit);
        return toAjax(save);
    }
    @PutMapping("/update")
    @Operation(summary = "修改商品单位数量")
    public AjaxResult update(@RequestBody @Validated ProductUnit productUnit){
        String name = productUnit.getName();
        Long id = productUnit.getId();
        ProductUnit one = productUnitService.getOne(Wrappers.lambdaQuery(ProductUnit.class).eq(ProductUnit::getName, name));
        if(one!=null&&one.getId()!=id){
            return AjaxResult.error("该单位已经存在");
        }
        boolean b = productUnitService.updateById(productUnit);
        return toAjax(b);
    }
    @DeleteMapping("/{ids}")
    @Operation(summary="删除商品数量单位")
    public AjaxResult deleteByIds (@PathVariable Long[] ids){
        return toAjax(productUnitService.removeBatchByIds(Arrays.stream(ids).toList()));
    }


}
